<template>
  <v-data-table
    :headers="headers"
    :search="search"
    :loading="loading"
    :items="userList"
    :options.sync="options"
    sort-by="USER_ID"
    class="elevation-1"
  >
    <template v-slot:top>
      <v-toolbar
        flat
      >
        <v-toolbar-title>Admin</v-toolbar-title>
        <v-divider
          class="mx-4"
          inset
          vertical
        ></v-divider>
        <v-spacer></v-spacer>
        <v-text-field
          v-model="search"
          append-icon="mdi-magnify"
          label="查找..."
          single-line
          hide-details
        ></v-text-field>
        <v-dialog
          v-model="dialog"
          max-width="500px"
        >
          <template v-slot:activator="{ on, attrs }">
            <v-btn
              color="primary"
              dark
              class="mb-2"
              v-bind="attrs"
              v-on="on"
            >
              新建角色
            </v-btn>
          </template>
          <v-card>
            <v-card-title>
              <span class="text-h5">分配角色</span>
            </v-card-title>
            <v-divider/>
            <v-card-text>
              <v-container>
                <v-row>
                  <v-col
                    cols="12"
                    sm="6"
                    md="4"
                  >
                    <v-select
                      v-model="editedSelect"
                      :hint="`${editedSelect.role}, ${editedSelect.roleId}`"
                      :items="editedSelectItems"
                      item-text="role"
                      item-value="roleId"
                      label="分配角色"
                      persistent-hint
                      return-object
                      single-line
                    ></v-select>
                  </v-col>
                </v-row>
              </v-container>
            </v-card-text>

            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn
                color="blue darken-1"
                text
                @click="close"
              >
                Cancel
              </v-btn>
              <v-btn
                color="blue darken-1"
                text
                @click="save"
              >
                Save
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
        <v-dialog v-model="dialogDelete" max-width="500px">
          <v-card>
            <v-card-title class="text-h5">你确定要删除 ID 为 {{ editedId }} 的用户?</v-card-title>
            <v-divider/>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="blue darken-1" text @click="closeDelete">Cancel</v-btn>
              <v-btn color="blue darken-1" text @click="deleteItemConfirm">OK</v-btn>
              <v-spacer></v-spacer>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-toolbar>
    </template>
    <template v-slot:item.ROLE_ID="{ item }">
      <v-chip
        :color="getColor(item.ROLE_ID)"
        dark
        @click="editItem(item)"
      >
        {{ item.ROLE_ID }}
      </v-chip>
    </template>
    <template v-slot:item.actions="{ item }">
      <v-icon
        small
        class="mr-2"
        @click="editItem(item)"
      >
        mdi-pencil
      </v-icon>
      <v-icon
        small
        @click="deleteItem(item)"
      >
        mdi-delete
      </v-icon>
    </template>
    <template v-slot:no-data>
      无数据
    </template>
  </v-data-table>
</template>

<script>
  import userApi from '@/api/apiPath/userApi'
  export default {
    name: 'AdminConsole',
    data() {
      return {
        dialog: false,
        dialogDelete: false,
        search: '',
        totalUser: 0,
        userList: [],
        loading: true,
        options: {},
        headers: [
          {
            text: '用户ID',
            align: 'start',
            sortable: true,
            value: 'USER_ID'
          },
          { text: '昵称',sortable: true, value: 'NICK_NAME' },
          { text: '邮箱',sortable: true, value: 'EMAIL' },
          { text: '角色',sortable: true, value: 'ROLE_ID' },
          { text: '创建时间',sortable: true, value: 'CREATED_TIME' },
          { text: '操作', value: 'actions', sortable: false }
        ],
        editedId: '',
        editedSelect: {

        },
        editedSelectItems: [
          {
            role: '管理员',
            roleId: '1001'
          },
          {
            role: '组织者',
            roleId: '1002'
          },
          {
            role: '普通用户',
            roleId: '1003'
          }
        ],
        roleMap: {
          1001: '管理员',
          1002: '组织者',
          1003: '普通用户'
        },
        editedIndex: -1,
        editedItem: {
          name: '',
          calories: 0,
          fat: 0,
          carbs: 0,
          protein: 0
        },
        defaultItem: {
          name: '',
          calories: 0,
          fat: 0,
          carbs: 0,
          protein: 0
        }
      }
    },
    watch: {
      options: {
        handler () {
          this.getUserList()
        },
        deep: true
      },
      dialog (val) {
        val || this.close()
      },
      dialogDelete (val) {
        val || this.closeDelete()
      }
    },
    computed: {
      formTitle () {
        return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
      }
    },
    methods: {
      getUserList() {
        const { page, itemsPerPage } = this.options
        this.loading = true
        userApi.getUserList({ page: page, pageNumber: itemsPerPage }).then(res => {
          this.userList = res.data.items
          this.totalUser = res.data.total
          this.loading = false
        })

      },
      editItem (item) {
        const currentRoleId = item.ROLE_ID
        this.editedId = item.USER_ID
        this.editedSelect = Object.assign({},{
          role: this.roleMap[currentRoleId],
          roleId: currentRoleId
        })
        this.dialog = true
      },

      deleteItem (item) {
        this.editedId = item.USER_ID
        this.dialogDelete = true
      },

      deleteItemConfirm () {
        const _this = this
        userApi.deleteUserById(this.editedId).then(() => {
          _this.$toast.success('删除成功')
          _this.getUserList()
        })
        this.closeDelete()
      },

      close () {
        this.editedSelect = {}
        this.dialog = false
        this.$nextTick(() => {
          this.editedItem = Object.assign({}, this.defaultItem)
          this.editedIndex = -1
        })
      },

      closeDelete () {
        this.dialogDelete = false
        this.$nextTick(() => {
          this.editedItem = Object.assign({}, this.defaultItem)
          this.editedIndex = -1
        })
      },

      save () {
        const _this = this
        const data = {
          id: this.editedId,
          newRoleId: this.editedSelect.roleId
        }
        console.log(data)
        userApi.allocateRole(data).then(() => {
          _this.$toast.success('分配成功')
          _this.getUserList()
        })
        this.close()
      },
      getColor (role) {
        if (role === '1001' ) return 'blue'
        else if (role === '1002') return 'orange'
        else return 'green'
      }
    },
     mounted() {
      this.getUserList()
    }
  }
</script>

<style scoped>

</style>
